'use strict'

/***
 ** Api 操作类
***/
import axios from 'axios'
import sha1 from 'crypto-js/sha1';
import Configs from './Configs'
import Utils from './Utils'
import Session from './Session'
import Router from '../router'

axios.defaults.baseURL = Configs.USER_SERVER_URL;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//接口列表
const APIMAP = {
	CUSTOMER: {
		'telLogin': 'telLogin',
		'loginId': 'loginId',
		'menuList': 'menuList',
		'bulletinBoard': 'bulletinBoard/:uid',
		'reservation': 'reservation',
		'bill': 'bill'
	},
	MANAGE: {
		'login': 'login/:uid',
		'loginId': 'loginId',
		'menuList': 'menuList',
		'mansionList': 'mansionList',
		'reportTemplateList': 'reportTemplateList'
	}
}


//POST传参序列化
axios.interceptors.request.use((config) => {
	const timestamp = Utils.timestamp();
	const nonce = Utils.nonce();
	let signParams = {
		timestamp: timestamp,
        nonce: nonce,
        signature: sha1(timestamp + nonce + Configs.API_SIGNATURE_KEY).toString()
	}
	/***
	 ** axios请求参数注解
	 ** get,delete: 参数使用params提交
	 ** post,put: 参数使用data提交
	***/
    if (config.method == 'get' || config.method == 'delete') {
  	    config.params = Object.assign(config.params || {}, signParams);
    } else {
  	    config.data = Object.assign(config.data || {}, signParams);
    }

    //Header加入token
    if (Session.getApiAccessToken()) {
  	    config.headers['Api-Access-Token'] = Session.getApiAccessToken();
    }
    return config;
}, (error) =>{
  return Promise.reject(error);
});


//返回状态判断
axios.interceptors.response.use((res) => {
	//301 重新登录
	if (res.data.code == 301 || res.data.code == 302) {
		Session.removeApiAccessToken();
		let roleMode = Session.getRoleMode() || 'customer';
		Router.replace({
			path: '/' + roleMode + '/login'
    	});
        Toast({
            message: res.data.message,
            position: 'bottom',
            duration: 3000
        });
		return;
	}
    return res;
}, (error) => {
	//301 重新登录
	if (error.response.status == 301 || error.response.status == 302) {
		Session.removeApiAccessToken();
		let roleMode = Session.getRoleMode() || 'customer';
		Router.replace({
			path: '/' + roleMode + '/login'
    	});
        Toast({
            message: res.data.message,
            position: 'bottom',
            duration: 3000
        });
		return;
	} else {
        Toast({
            message: Strings.Errors.ERR0001,
            position: 'bottom',
            duration: 3000
        });
        return Promise.reject(error);
    }
});



//配置axios
let initApiConfig = (key, params) => {
    let roleMode = Session.getRoleMode();
    console.log(roleMode)
	let apiPlt = APIMAP.CUSTOMER;
	if (roleMode == 'customer') {
		axios.defaults.baseURL = Configs.CUSTOMER_SERVER_URL;
		apiPlt = APIMAP.CUSTOMER;
	} else {
		axios.defaults.baseURL = Configs.MANAGE_SERVER_URL;
		apiPlt = APIMAP.MANAGE;
	}

	//返回请求路径
	let url = apiPlt[key];
	if (params && params['uid'] && url.indexOf(':uid') > -1) {
		let newUrl = url.replace(':uid', params['uid']);
		return newUrl;
	} else if (url.indexOf(':uid') > -1) {
		return url.replace(':uid', '');
	}
	return url;
}

/***
 ** 暴露请求方法
***/
export default {
	get: (key, params) => {
		let url = initApiConfig(key, params);
		return axios.get(url, {params: params});
	},

	post: (key, data) => {
		let url = initApiConfig(key, data);
		return axios.post(url, data);
	},

	put: (key, data) => {
		let url = initApiConfig(key, data);
		return axios.put(url, data);
	},

	delete: (key, params) => {
		let url = initApiConfig(key, params);
		return axios.delete(url, {params: params});
	}
}